<script lang="ts" setup>
import * as echarts from 'echarts';
import { SimpleScrollbar } from '@sa/materials';
import { onMounted, ref } from 'vue';
import { useRoute } from 'vue-router';
import { startEndtime } from '@/utils/common';
import { sensorIcon } from '@/enum/icon';
import { DeviceInfoList, HistoryData4Curve } from '@/service/api/bigScreen';
import DeviceDetail from '@/views/breedingManage/deviceManage/modules/device-detail.vue';
import FishSelect from './fish-select.vue';

const route = useRoute();
const farmId = route.query.farmId ? route.query.farmId : '';

// 获取传感器数据
const sensorList = ref([]);
const FishSelect1 = ref();
const FishSelect2 = ref();
const getDeviceInfoList = obj => {
  DeviceInfoList(obj).then(res => {
    sensorList.value = res.data?.data;
    // 获取传感器采集数据
    if (sensorList.value.length > 1) {
      getHistoryData4Curve(sensorList.value[1].id, 0);
      getHistoryData4Curve(sensorList.value[0].id, 1);
      setTimeout(() => {
        FishSelect1.value?.setCheckId(sensorList.value[1].id, sensorList.value[1].deviceName);
        FishSelect2.value?.setCheckId(sensorList.value[0].id, sensorList.value[0].deviceName);
      });
      return false;
    }
    getHistoryData4Curve(sensorList.value[0].id, 0);
    setTimeout(() => {
      FishSelect1.value?.setCheckId(sensorList.value[0].id, sensorList.value[0].deviceName);
    });
  });
};

const setEchartsInfo = (arr, arr1, type) => {
  const chart = echarts.init(echartsRef.value);
  const chart1 = echarts.init(echartsRef1.value);
  if (type === 0) {
    chart.setOption(EchartsOption(arr, arr1));
  } else {
    chart1.setOption(EchartsOption(arr, arr1));
  }
};

// 获取趋势图数据
const getHistoryData4Curve = (deviceId, type) => {
  const { startTime, endTime } = startEndtime();
  const obj = {
    startTime,
    endTime,
    deviceId
  };
  HistoryData4Curve(obj).then(res => {
    const arr = []; // 采集时间
    const arr1 = []; // 采集数值
    const _data = res.data;
    chartsData.value[type] = {
      arr,
      arr1
    };
    if (_data.length > 0) {
      _data.forEach(item => {
        arr.push(item.time.split(' ')[1]);
        arr1.push(item.average);
      });
      setEchartsInfo(arr, arr1, type);
    }
  });
};
const EchartsOption = (data, list) => {
  return {
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data,
      axisLabel: {
        textStyle: {
          color: '#A2DEFF'
        }
      }
    },
    grid: {
      top: 20,
      bottom: 30
    },
    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
      { offset: 0, color: '#3758fd' }, // 0% 处的颜色
      // {offset: 0.5, color: '#d9c9b7'}, // 50% 处的颜色
      { offset: 1, color: '#379afd' } // 100% 处的颜色
    ]),
    yAxis: {
      type: 'value',
      axisLabel: {
        textStyle: {
          color: '#A2DEFF'
        }
      },
      splitLine: {
        show: true, // 显示网格线
        lineStyle: {
          color: ['#21466A'], // 网格线颜色
          width: 1, // 网格线宽度
          type: 'solid' // 网格线类型，这里设置为虚线
        }
      }
    },
    series: [
      {
        data: list,
        type: 'line',
        areaStyle: {},
        smooth: true
      }
    ]
  };
};

const ModalEchartsOption = (data, list) => {
  return {
    tooltip: {
      trigger: 'axis',
      textStyle: {
        fontSize: 16
      }
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data,
      axisLabel: {
        fontSize: 16
      }
    },
    grid: {
      top: 40,
      bottom: 30,
      left: 40,
      right: 30
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        fontSize: 16
      },
      splitLine: {
        show: true, // 显示网格线
        lineStyle: {
          color: ['#21466A'], // 网格线颜色
          width: 1, // 网格线宽度
          type: 'solid' // 网格线类型，这里设置为虚线
        }
      }
    },
    series: [
      {
        data: list,
        type: 'line',
        areaStyle: {},
        smooth: true
      }
    ]
  };
};

let echartsRef = ref(null);
let echartsRef1 = ref(null);

onMounted(() => {
  const obj = {
    deviceType: 1,
    farmId,
    pageSize: 1000
  };
  // 获取传感器数据
  getDeviceInfoList(obj);
});

// 返回传感器图标
const getIconPath = code => {
  if (sensorIcon.hasOwnProperty(code)) {
    return sensorIcon[code];
  }
  return '/src/assets/imgs/ty@2x.png';
};

/* 传感器曲线图弹出框 */
const chartsData = ref({});
const modalVisible = ref(false);
const echartsModalRef = ref(null);

const getHistoryData4CurveById = async (deviceId: any) => {
  const { startTime, endTime } = startEndtime();
  const obj = {
    startTime,
    endTime,
    deviceId
  };
  const res = await HistoryData4Curve(obj);
  const arr: any = []; // 采集时间
  const arr1: any = []; // 采集数值
  const data = res.data;
  if (data.length > 0) {
    data.forEach((item: any) => {
      arr.push(item.time.split(' ')[1]);
      arr1.push(item.average);
    });
  }
  return {
    arr,
    arr1
  };
};

const showChartsModal = async (type: number, id?: string) => {
  modalVisible.value = true;
  if (type === 3) {
    const { arr, arr1 } = await getHistoryData4CurveById(id);
    setTimeout(() => {
      setModalEchartsInfo(arr, arr1, 0);
    }, 100);
    return;
  }
  setTimeout(() => {
    setModalEchartsInfo(chartsData.value[type].arr, chartsData.value[type].arr1, type);
  }, 100);
};

const setModalEchartsInfo = (arr: any, arr1: any, type: number) => {
  const chart = echarts.init(echartsModalRef.value);
  if (type === 0) {
    chart.setOption(ModalEchartsOption(arr, arr1));
  } else {
    chart.setOption(ModalEchartsOption(arr, arr1));
  }
};
/* 传感器曲线图弹出框 */

/* 传感器详情 */
const showBtn1 = ref(false);
const showBtn2 = ref(false);
const hostData = defineModel<any>('hostData', {
  default: []
});
const farmData = defineModel<any>('farmData', {
  default: []
});

const DeviceDetailRef = ref();

const setShowBtnVisible = async (type: number) => {
  if (type === 1) showBtn1.value = true;
  if (type === 2) showBtn2.value = true;
};

const getDetail = (type: number, item?: any) => {
  let id: any = '';
  if (type === 3) {
    id = item.id;
    item.btnshow = false;
  } else {
    id = document.getElementById(`FishSelect${type}`)?.dataset.id;
  }
  const data = sensorList.value.find(item => item.id.toString() === id.toString());
  DeviceDetailRef.value?.setRowData(data);
};
/* 传感器详情 */

/* 控制实时指标颜色 */
const setSensorClass = (item: any): string => {
  if (item.online === false) return 'showTextRed';
  if (item.field < item.lowAlarm || item.field > item.hiAlarm) return 'showTextRed';
  return '';
};
</script>

<template>
  <div>
    <div class="Card">
      <div class="card-header">
        <img src="../../../assets/imgs/breedDetails/title_sszb@2x.png" alt="" />
      </div>
      <div class="card-warp">
        <SimpleScrollbar>
          <div class="warp">
            <template v-for="(item, index) in sensorList" :key="index">
              <div
                v-if="item.isShow"
                class="warp-item"
                :class="setSensorClass(item)"
                style="cursor: pointer; position: relative"
                oncontextmenu="return false"
                @dblclick="showChartsModal(3, item.id)"
                @click.right="item.btnshow = true"
                @click.left="item.btnshow = false"
              >
                <img :src="getIconPath(item.categoryCode)" alt="" />
                <div>
                  <span>{{ item.deviceName }}</span>
                  <span>
                    {{ item.field || 0 }}
                    <span style="font-size: 12px">{{ item.unit }}</span>
                  </span>
                </div>
                <div
                  v-if="item.btnshow"
                  style="position: absolute; top: 50%; left: 30%; transform: translate(-50%, -50%)"
                  @click.stop
                >
                  <AButton @click="getDetail(3, item)">查看详情</AButton>
                </div>
              </div>
            </template>
          </div>
        </SimpleScrollbar>
      </div>
    </div>
    <div class="Card1">
      <div class="card1-warp">
        <div class="card1-header">
          <img src="../../../assets/imgs/breedDetails/title_cgq@2x.png" alt="" />
          <FishSelect
            v-if="sensorList.length > 0"
            id="FishSelect1"
            ref="FishSelect1"
            :list="sensorList"
            hide="0"
            @change="id => getHistoryData4Curve(id, 0)"
          />
        </div>
        <div
          ref="echartsRef"
          class="echarts"
          oncontextmenu="return false;"
          @click.right="setShowBtnVisible(1)"
          @click.left="showBtn1 = false"
          @dblclick="showChartsModal(0)"
        ></div>
        <div v-if="showBtn1" class="chart-btn-wrapper1">
          <AButton class="chart-btn" @click="getDetail(1)">查看详情</AButton>
        </div>
        <div class="card1-header">
          <img src="../../../assets/imgs/breedDetails/title_cgq@2x.png" alt="" />
          <FishSelect
            v-if="sensorList.length > 0"
            id="FishSelect2"
            ref="FishSelect2"
            :list="sensorList"
            hide="1"
            @change="id => getHistoryData4Curve(id, 1)"
          />
        </div>
        <div v-if="showBtn2" class="chart-btn-wrapper2">
          <AButton class="chart-btn" @click="getDetail(2)">查看详情</AButton>
        </div>
        <div
          ref="echartsRef1"
          oncontextmenu="return false;"
          class="echarts"
          @click.right="setShowBtnVisible(2)"
          @click.left="showBtn2 = false"
          @dblclick="showChartsModal(1)"
        ></div>
      </div>
    </div>

    <div>
      <AModal v-model:open="modalVisible" :footer="null" :width="1366" title="传感器详情" destroy-on-close>
        <div class="pt-20px">
          <div ref="echartsModalRef" style="width: 100%; height: 600px"></div>
        </div>
      </AModal>
    </div>

    <div>
      <DeviceDetail ref="DeviceDetailRef" v-model:hostData="hostData" v-model:farmData="farmData" :disabled="false" />
    </div>
  </div>
</template>

<style lang="scss" scoped>
.Card1 {
  width: 450px;
  height: 560px;
  background-image: url('@/assets/imgs/breedDetails/bg_cgq@2x.png');
  background-size: 100% 100%;
  background-repeat: no-repeat;
  display: flex;
  flex-direction: column;

  .card1-header {
    display: flex;
    align-items: center;

    img {
      width: 90px;
      height: 34px;
    }
  }

  .card1-warp {
    flex: 1;
    display: flex;
    flex-direction: column;
    margin: 30px;
    position: relative;

    .chart-btn-wrapper1 {
      position: absolute;
      left: 50%;
      top: 25%;
      transform: translateX(-50%);
      z-index: 9;
    }
    .chart-btn-wrapper2 {
      position: absolute;
      left: 50%;
      top: 70%;
      transform: translateX(-50%);
      z-index: 9;
    }
    .echarts {
      flex: 1;
    }
  }
}

.Card {
  width: 450px;
  height: 360px;
  background-image: url('@/assets/imgs/breedDetails/bg_sszb@2x.png');
  background-size: 100% 100%;
  background-repeat: no-repeat;
  display: flex;
  flex-direction: column;

  .card-header {
    width: 100px;
    height: 50px;
    padding-top: 25px;
    margin-left: 20px;
  }

  .card-warp {
    flex: 1;
    padding: 10px 20px 0 20px;
    margin-bottom: 35px;
    overflow: auto;

    .warp {
      padding-top: 30px;
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      grid-gap: 12px 0;

      &-item {
        display: flex;
        margin-left: 30px;

        img {
          width: 60px;
          height: 60px;
        }

        div {
          display: flex;
          justify-content: center;
          flex-direction: column;
          margin-left: 21px;

          span {
            &:nth-child(1) {
              font-weight: 400;
              font-size: 14px;
              color: #83fff1;
            }

            &:nth-child(2) {
              font-weight: bold;
              font-size: 22px;
              color: #ffffff;
              line-height: 33px;
              letter-spacing: 1px;
            }
          }
        }
      }
    }
  }
}

.showTextRed {
  span {
    color: red !important;
  }
}
</style>
